package com.shushan.util;

import android.app.Activity;
import android.widget.Button;

/**
 * @ClassName: VerifyTools
 * @Desciption: 短信验证码工具类
 * @author: yichaohua
 * @date: 2018-01-15
 */
public class VerifyTools {

    private final static int TIME_TRY = 60;

    private int times = TIME_TRY;

    private boolean exit = false;

    private static VerifyTools instance;

    private Thread mThread;

    public static VerifyTools getInstance() {

        if (instance == null) {
            instance = new VerifyTools();
        }

        return instance;
    }

    public void startVerifyWaiting(final Activity act, final Button btnVerify) {

        exit = false;
        setVerifyLock(true, btnVerify);

        times = TIME_TRY;

        // 当线程不为空或存活时，杀死线程，目的防止多个线程同时运行
        if (mThread != null && mThread.isAlive()) {
            mThread.interrupt();
        }

        mThread = new Thread(new Runnable() {

            public void run() {
                try {
                    while (--times >= 0) {
                        if (exit) {
                            break;
                        }
                        updateVerifyUI(act, times, btnVerify);
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    updateVerifyUI(act, 0, btnVerify);
                }
                updateVerifyUI(act, 0, btnVerify);
            }
        });

        mThread.start();

    }

    private void setVerifyLock(boolean lock, Button btnVerify) {

        btnVerify.setEnabled(!lock);
        if (!lock) {
            btnVerify.setText("获取验证码");
        }
    }

    private void updateVerifyUI(Activity act, final int time, final Button btnVerify) {

        act.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnVerify.setText(times + "秒后重获");

                if (times <= 0) {
                    setVerifyLock(false, btnVerify);
                }
            }
        });
    }

    public void exit() {
        exit = true;
    }

    public void stopWaiting(final Activity act, final Button btnVerify) {
        if (mThread != null && mThread.isAlive()) {
            mThread.interrupt();
        }
        mThread = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                act.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        setVerifyLock(false, btnVerify);
                    }
                });
            }
        });
        mThread.start();

    }
}
